/**
 * 
 */
package src.edu.wayne.cs.csc4110.hw6.plugins;

import java.util.HashSet;

import javax.swing.JPanel;

import src.edu.wayne.cs.csc4110.hw6.implementations.dbase.UserImpl;
import src.edu.wayne.cs.csc4110.hw6.interfaces.Game;
import src.edu.wayne.cs.csc4110.hw6.interfaces.PluginToFrameWorkInterface;
import src.edu.wayne.cs.csc4110.hw6.interfaces.GameUser;

/**
 * @author Daniel
 *
 */
public abstract class GamePlugin extends JPanel implements Game{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 5698460673696785257L;
	private HashSet<GameUser> playerList;
	protected GameUser currentUser;
	private String gameName;
	
	protected final PluginToFrameWorkInterface frameWork;
	
	GamePlugin(PluginToFrameWorkInterface frameWork){
		this.frameWork = frameWork;
		if (gameName == null)
			gameName = new String("abstractGame");
	}

	public HashSet<GameUser> getPlayerList() {
		return playerList;
	}

	protected void setPlayerList(HashSet<GameUser> hashSet) {
		this.playerList = hashSet;
	}
	
	protected void setGameName(String gameName){
		this.gameName = gameName;
	}

	@Override
	public String getGameName() {
		return gameName;
	}

	public GameUser getNextPlayer()
	{
		GameUser nextUser = null;
		if (playerList == null)
		{
			playerList = frameWork.getPlayersInSession();
	
			for(GameUser user: playerList)
			{
				if(user != null){
					nextUser = user;
					break;
				}
			}
		}
		else
		{
			int count = 0;
			for(GameUser user: playerList)
			{
				if(user != null){
					count++;
				}
			}
			
			GameUser [] users = new UserImpl[count];
			count = 0;
			for(GameUser user: playerList)
			{
				if(user != null){
					users[count] = user;
					count++;
				}
			}
			
			
			if ( users.length > 1 )
			{		
				
				int i;
				int index = -1;
				
				for (i=0;i < users.length;i++)
				{
					if ( users[i].equals(currentUser) ){
						index = i;
						break;
					}
				}
				
				if (index < (users.length - 1))
				{
					nextUser = users[index + 1];
				}
				else
				{
					nextUser = users[0];
				}
			}
		}
		
		if (nextUser == null)
		{
			nextUser = currentUser;
		}
		return nextUser;
		
	}

	public GameUser getCurrentUser() {
		return currentUser;
	}

	public void setCurrentUser(GameUser currentUser) {
		this.currentUser = currentUser;
	}
	
	public void endGame(){
		frameWork.endGame();
	}
}
